<template>
  <el-drawer v-model="drawer" size="40%" direction="rtl" :with-header="false">
    <header>
      <h3>当前绑定的房间是：【{{ title }}】</h3>
    </header>
    <div style="display: flex;justify-content: space-between;margin-top: 20px;">
      <el-input style="width: 60%;" v-model="keyword" placeholder="筛选" maxlength="20"></el-input>
      <el-button type="primary" @click="handleSubmit" icon="check" style="padding:8px 16px!important;">确定</el-button>
    </div>
    <div class="bind-box">
      <el-tree
          ref="treeRef"
          :data="pools"
          @check-change="handleSelectNodes"
          show-checkbox
          node-key="id"
          default-expand-all
          highlight-current
          :filter-node-method="filterNode"
          :props="defaultProps"
      />
    </div>
  </el-drawer>
</template>

<script setup>
import { roomPools,bindPool } from '@/api/room.js'
import { list } from '@/api/pool.js'
import KVA from '@/utils/kva.js'
// 获取tree的实例
const treeRef = ref(null)

const drawer = ref(false)
const title = ref("")
const pools = ref([])
const bindPools = ref([])
const room_id = ref(0)
// 搜索菜单信息
const keyword = ref("")
// 菜单映射字段
const defaultProps = {
  children: 'children',
  label: 'name',
}


// 打开抽屉
const handleOpen = async (role) => {
  title.value = role.room_name
  room_id.value = role.room_id
  drawer.value = true
  pools.value = []
  bindPools.value = []
  const res = await roomPools(role.room_id)
  res.data?.forEach(item=>{
    pools.value.push({id:item.cooling_pool_id,name:item.cooling_pool_name})
    bindPools.value.push(item.cooling_pool_id)
  })
  const res2 = await list({room_id:0})
  res2.data?.forEach(item=>{
    pools.value.push({id:item.cooling_pool_id,name:item.cooling_pool_name})
  })
  treeRef.value.setCheckedKeys(bindPools.value)

}

// 点击菜单获取节点信息
const handleSelectNodes = ()=>{
  bindPools.value = treeRef.value.getCheckedKeys();
}
// 过滤节点
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}
// 监听
watch(keyword, (val) => {
  treeRef.value?.filter(val)
})

// 开始绑定
const handleSubmit = async () => {
  // 获取所有选中的节点
  let selectNodesIds = treeRef.value.getCheckedKeys();
  if(selectNodesIds && selectNodesIds.length == 0){
    KVA.notifyError("请选择一个项进行操作!!!")
    return;
  }
  // 开始获取
  const ids = selectNodesIds.join(",")
  const res = await bindPool({room_id:room_id.value,pool_ids:ids})
  KVA.notifySuccess("授权成功!!!")
  drawer.value = false
}
// 暴露方法给外部组件调用
defineExpose({
  handleOpen
})
</script>

<style scoped lang="scss">
.bind-box{
  margin: 24px 0;
}
</style>
